package com.ruirui.arraylist;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;

public class InsertElement {

    /**
     * 插入元素
     * @param args
     * @param index
     * @param value
     * @return
     * @param <T>
     */
    public static<T> T[] insertElement(T[] args, int index, T value) {
        if (index < 0 || index > args.length)
            throw new IndexOutOfBoundsException();
        T[] ints = Arrays.copyOf(args, args.length + 1);
        // 起始数组 起始位置 目标数组 目标位置 复制元素数量
        System.arraycopy(args, index, ints, index + 1, args.length - index);
        ints[index] = value;
        return ints;
    }

    public static <T> Object[] insertElementStream(T[] args, T indexElement, T value) {
       AtomicBoolean flag = new AtomicBoolean(false);
        return Arrays.stream(args).flatMap(
                integer -> {
                    if (integer == indexElement && !flag.get()) {
                        flag.set(true);
                        return Stream.of(integer, value);
                    }
                    return  Stream.of(integer);
                }
        ).toArray();
    }


}
